package com.renfei.filtercamera;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.app.Dialog;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.VideoView;

import com.cgfay.uitls.dialog.DialogBuilder;
import com.cgfay.uitls.utils.FileUtils;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.renfei.medialibrary.FFmpegPlayer;
import com.renfei.medialibrary.VideoPlayGlSurfaceView;
import com.renfei.medialibrary.VideoTimeInfo;
import com.renfei.medialibrary.listener.OnPlayerCompleteListener;
import com.renfei.medialibrary.listener.OnPlayerErrorListener;
import com.renfei.medialibrary.listener.OnPlayerLoadListener;
import com.renfei.medialibrary.listener.OnPlayerParparedListener;
import com.renfei.medialibrary.listener.OnPlayerStatusChangeListener;
import com.renfei.medialibrary.listener.OnVideoPlayInfoListener;
import com.renfei.medialibrary.listener.OnYuvDataCallBackListener;
import com.renfei.medialibrary.util.MuteEnum;
import com.renfei.medialibrary.util.TimeUtil;

import java.lang.ref.WeakReference;

public class    VideoEditActivity extends AppCompatActivity implements View.OnClickListener {

    //    public static final String VIDEO_PATH = "videoPath";
    private static final String TAG = VideoEditActivity.class.getSimpleName();

    VideoPlayGlSurfaceView glSurfaceView;
    TextView tvCurrentTime;
    SeekBar tvSeekBar;
    TextView tvTotalTime;
    LinearLayout ll_edit_btn;
    FloatingActionButton fab_close;
    FloatingActionButton fab_success;


    private FFmpegPlayer fFmpegPlayer;
    private PlayTimeHandler playTimeHandler;

    private boolean isSeekBar = false;
    private int currentPosition = 0;

    private String VideoPath = "";


    // 当前对话框
    private Dialog mDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_video_edit);

        VideoPath = getIntent().getStringExtra(Constant.VIDEO_PATH);
        Log.e(TAG, "videoPath: " + VideoPath);

        glSurfaceView = findViewById(R.id.glSurfaceView);
        tvCurrentTime = findViewById(R.id.tv_current_time);
        tvSeekBar = findViewById(R.id.tv_seek_bar);
        tvTotalTime = findViewById(R.id.tv_total_time);
        ll_edit_btn = findViewById(R.id.ll_edit_btn);
        fab_close = findViewById(R.id.fab_close);
        fab_success = findViewById(R.id.fab_success);

        fab_close.setOnClickListener(this);
        fab_success.setOnClickListener(this);


        fFmpegPlayer = new FFmpegPlayer();
        fFmpegPlayer.setGlSurfaceView(glSurfaceView);

        fFmpegPlayer.setVolume(50);
        fFmpegPlayer.setMute(MuteEnum.MUTE_CENTER);

        fFmpegPlayer.setOnPlayerParparedListener(new OnPlayerParparedListener() {
            @Override
            public void onParpared() {
                Log.e(TAG, "onParpared :开始加载视频资源 ");
                fFmpegPlayer.startPlay();
            }
        });
        fFmpegPlayer.setOnPlayerLoadListener(new OnPlayerLoadListener() {
            @Override
            public void onLoad(boolean load) {
                if (load) {
                    Log.e(TAG, "加载中...");
                } else {

                    Log.e(TAG, "加载已完成: ");
                }

            }
        });
        fFmpegPlayer.setOnPlayerErrorListener(new OnPlayerErrorListener() {
            @Override
            public void onError(int code, String msg) {
                Log.e(TAG, "code: " + code + "     msg: " + msg);
            }
        });
        fFmpegPlayer.setOnPlayerStatusChangeListener(new OnPlayerStatusChangeListener() {
            @Override
            public void onPause(boolean isPause) {
                if (isPause) {
                    Log.e(TAG, "暂停播放: ");
                } else {
                    Log.e(TAG, "开始播放: ");
                }
            }
        });
        fFmpegPlayer.setOnPlayerCompleteListener(new OnPlayerCompleteListener() {
            @Override
            public void onComplete() {
                Log.e(TAG, "onComplete 方法回调完成: ");
                ll_edit_btn.setVisibility(View.VISIBLE);
            }
        });
        fFmpegPlayer.setOnYuvDataCallBackListener(new OnYuvDataCallBackListener() {
            @Override
            public void onYuvDataCallBack(int width, int height, byte[] y, byte[] u, byte[] v) {

            }
        });
        fFmpegPlayer.setOnVideoPlayInfoListener(new OnVideoPlayInfoListener() {
            @Override
            public void onVideoPlayInfo(VideoTimeInfo timeInfo) {

                Log.e(TAG, "onVideoPlayInfo: currentTime " + timeInfo.getCurrentTime()
                        + "   totalTime = " + timeInfo.getTotalTime());
                Message message = new Message();
                message.what = 0;
                message.obj = timeInfo;
                playTimeHandler.sendMessage(message);
            }
        });
        tvSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if (fFmpegPlayer.getDuration() > 0 && isSeekBar) {
                    currentPosition = fFmpegPlayer.getDuration() * progress / 100;
                }
                Log.e(TAG, "onProgressChanged: duration " + fFmpegPlayer.getDuration());
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                isSeekBar = true;
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                isSeekBar = false;
                fFmpegPlayer.seek(currentPosition);

            }
        });

        playTimeHandler = new PlayTimeHandler(new WeakReference<>(this));


        fFmpegPlayer.setSource(VideoPath);
        fFmpegPlayer.parpared();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.fab_close:
                deleteRecordedVideo();
                break;
            case R.id.fab_success:
                //视频上传


                break;
        }
    }

    /**
     * 删除已录制的视频
     */
    private void deleteRecordedVideo() {
        dismissDialog();
        mDialog = DialogBuilder.from(this, R.layout.dialog_two_button)
                .setText(R.id.tv_dialog_title, R.string.delete_last_video_tips)
                .setText(R.id.btn_dialog_cancel, R.string.btn_dialog_cancel)
                .setDismissOnClick(R.id.btn_dialog_cancel, true)
                .setText(R.id.btn_dialog_ok, R.string.btn_delete)
                .setDismissOnClick(R.id.btn_dialog_ok, true)
                .setOnClickListener(R.id.btn_dialog_ok, v -> {
                    if (!TextUtils.isEmpty(VideoPath)) {
                        FileUtils.deleteFile(VideoPath);
                    }
                    VideoEditActivity.this.finish();
                })
                .show();
    }

    /**
     * 销毁当前的对话框
     */
    private void dismissDialog() {
        if (mDialog != null) {
            mDialog.dismiss();
            mDialog = null;
        }
    }


    static class PlayTimeHandler extends Handler {
        private WeakReference<VideoEditActivity> weakReference;

        public PlayTimeHandler(WeakReference<VideoEditActivity> weakReference) {
            this.weakReference = weakReference;
        }

        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    VideoTimeInfo timeInfo = (VideoTimeInfo) msg.obj;
                    if (null != weakReference.get() && !weakReference.get().isSeekBar) {

                        if (null != weakReference.get().tvCurrentTime
                        ) {
                            weakReference.get().tvCurrentTime.setText(TimeUtil.secdsToDateFormat(timeInfo.getCurrentTime()));
                        }
                        if (null != weakReference.get().tvCurrentTime) {
                            weakReference.get().tvTotalTime.setText(TimeUtil.secdsToDateFormat(timeInfo.getTotalTime()));
                        }
                        if (null != weakReference.get().tvSeekBar) {
                            weakReference.get().tvSeekBar.setProgress(
                                    timeInfo.getCurrentTime() * 100 / timeInfo.getTotalTime()

                            );
                        }
                    }
                    break;
            }

        }
    }
}
